package com.lanou.test.service;

import com.lanou.test.bean.Role;
import com.lanou.test.bean.User;
import com.lanou.test.mapper.RoleMapper;
import com.lanou.test.mapper.UserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class LoginRealm extends AuthorizingRealm {

    @Autowired
    UserMapper mapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Role> list = roleMapper.selectRolesByUser(user);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        for (Role role : list) {
            info.addRole(role.getRoleName());
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username =(String)authenticationToken.getPrincipal();
        User user =mapper.selectUserByName(username);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPwd(),this.getName());
        return info;
    }

}
